package com.javafm.doc2jpg;

import org.apache.pdfbox.pdmodel.PDDocument;
import org.apache.pdfbox.pdmodel.PDPageTree;
import org.apache.pdfbox.rendering.PDFRenderer;
import org.jodconverter.core.document.DefaultDocumentFormatRegistry;
import org.jodconverter.core.office.OfficeException;
import org.jodconverter.core.office.OfficeManager;
import org.jodconverter.core.office.OfficeUtils;
import org.jodconverter.local.LocalConverter;
import org.jodconverter.local.office.LocalOfficeManager;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.*;

public class App {

    public void pdf2jpg(String pdfFile, String jpgFile) throws IOException {
        PDDocument doc = null;
        try {
            InputStream stream = new FileInputStream(new File(pdfFile));
            doc = PDDocument.load(stream);
            PDFRenderer pdfRenderer = new PDFRenderer(doc);
            PDPageTree pages = doc.getPages();
            int pageCount = pages.getCount();
            for (int i = 0; i < pageCount; i++) {
                BufferedImage bim = pdfRenderer.renderImageWithDPI(i, 200);
                try (ByteArrayOutputStream os = new ByteArrayOutputStream()) {
                    ImageIO.write(bim, "jpg", os);
                    byte[] datas = os.toByteArray();
                    try (OutputStream out = new FileOutputStream(String.format(jpgFile, i))) {
                        out.write(datas);
                    }
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }finally {
            if (doc != null) {
                doc.close();
            }
        }
    }

    public static void doc2pdf(String docFile, String pdfFile) throws OfficeException, FileNotFoundException {
        OfficeManager officeManager = LocalOfficeManager.builder()
                .install()
                .officeHome("D:\\app\\LibreOffice")
                .build();

        try {
            officeManager.start();

            // doc 转 pdf
            LocalConverter
                    .make()
                    .convert(new FileInputStream(docFile))
                    .to(new File(pdfFile))
                    .as(DefaultDocumentFormatRegistry.PDF)
                    .execute();
        } finally {
            OfficeUtils.stopQuietly(officeManager);
        }
    }

    public static void main(String[] args) throws IOException, OfficeException {
        String docFile = "E:\\data\\doc2jpg\\test.docx";
        String pdfFile = "E:\\data\\doc2jpg\\test.pdf";
        String jpgFile = "E:\\data\\doc2jpg\\%d.jpg";

        App app = new App();

        // 用 libreoffice 转换 doc 到 jpg 只能转换第一页
        // 所以要想一个中间办法，先转 pdf 再把 pdf 转 jpg

        // doc 转 pdf
        app.doc2pdf(docFile, pdfFile);

        // pdf 转 jpg
        app.pdf2jpg(pdfFile, jpgFile);

    }
}
